import type { DaemonSet } from "../../../api/k8s/types";

import { useK8SApi } from "../../../api/k8s/k8s";
import { SourceMan } from "../providers/sourceCtl";
import type { Ref } from "vue";
import type { DaemonSetQuery } from "../../../api/k8s/daemonset";
const { daemonSetRepo } = useK8SApi();

class DaemonSetProvider extends SourceMan<DaemonSet> {
  get daemonSetList(): Ref<DaemonSet[]> {
    return this.srcList;
  }

  // 获取节点列表
  getDaemonSets = async (req?: DaemonSetQuery) => {
    const res = await daemonSetRepo.getDaemonSet({
      ...(req || this.searchQuery.value),
      continue: this.continue,
      limit: this.pager.limit.value
    });
    if (res.ok) {
      this.continue = res.data.metadata.continue;
      this.srcList.value = res.data.items;
      this.pager.total.value =
        res.data.metadata.remainingItemCount ?? res.data.items.length;
    }
  };

  // 获取节点详情
  getDaemonSetDetails = async (ns: string, name: string) => {
    const res = await daemonSetRepo.getDaemonSetDetail({ namespace: ns, name });
    if (res.ok) {
      this.srcDetail.value = res.data;
      this.srcYamlContent.value = this.objectToYaml(res.data);
      this.yamlDialog.value = true;
    }
  };

  // 更新节点
  updateDaemonSet = async (namespace?: string, name?: string) => {
    const res = await daemonSetRepo.updateDaemonSet({ name, namespace });
    if (res.ok) {
      this.refreshDaemonSetList();
    }
  };

  // delete
  deleteDaemonSet = async (query: { namespace?: string; name?: string }) => {
    const res = await daemonSetRepo.deleteDaemonSet(query);
    if (res.ok) {
      this.refreshDaemonSetList();
    }
  };

  refreshDaemonSetList = async () => {
    this.continue = undefined;
    await this.getDaemonSets({});
  };
}

export default new DaemonSetProvider();
